package com.lkm.app_ui.m.Imple.sz_dataup;

import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;

import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.help.GsonHelp;
import com.lkm.comlib.fun_m.NetworkStateModule;
import com.lkm.frame.file.FileHelper;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.Base64Common;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.IOHelp;
import com.lkm.javatool.JsonP1;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m.dataUp.SZWeightInfo;
import com.lkm.market2_0.m_imple.newDataUp.NewDataUpParse;
import com.lkm.market2_0.m_imple.newDataUp.NewSZApi;
import com.lkm.market2_0.m_imple.newDataUp.SZWeightImg;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.task.DefaultTaskExecutor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;



class SZOrderUpTask extends TaskAdapter<Void, Object[], Void> {

    private Handler mainHandler;
    public SZOrderUpTask() {
        super(new DefaultTaskExecutor(true), SZOrderUpTask.class.getName(), AppConst.getTaskManager2());

        mainHandler = new Handler(Looper.getMainLooper());
    }


    private OrderCachePo orderCachePoUping;




    public void addUpOrder(SteelyardInfo steelyardInfo, OrderEntity orderEntity) {


        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                synchronized (SZOrderUpTask.this){
                    if (orderCachePoUping == null) {

                        orderCachePoUping = new OrderCachePo(steelyardInfo, orderEntity);
                    }else{

                        mTaskExecutor.executorDoAsyncExecuting(new Runnable() {
                            @Override
                            public void run() {
                                if (!getIsContinue()) return;
                                cacheUpOrder(steelyardInfo, orderEntity);
                            }
                        });
                    }
                }
            }
        },3000);


    }
    public boolean isSubmitWeightInfoing(){
        synchronized (SZOrderUpTask.this){
            return orderCachePoUping != null;
        }
    }


    @Override
    public void doExecuting(Void param) {
        super.doExecuting(param);
        mTaskExecutor.executorDoAsyncExecuting(new Runnable() {

            @Override
            public void run() {
                while (getIsContinue()){
                    try {
                        doex();
                    }catch (Exception e){

                        System.out.println("====sz"+e.getMessage());
                    }
                };
            }
        });
    }

    OrderCachePo tempOrderCachePo = null;
    private void doex(){
        long startTime = SystemClock.uptimeMillis();


        if(tempOrderCachePo == null) {
            String json = getCacheUpOrder();
            try {
                tempOrderCachePo = GsonHelp.fromJson(json, OrderCachePo.class);
            } catch (Exception e) {
            }
        }

        OrderCachePo canOrderCachePo = tempOrderCachePo;


        synchronized (SZOrderUpTask.this) {
            if (orderCachePoUping == null) {

                orderCachePoUping = canOrderCachePo;
            }else {
                canOrderCachePo = orderCachePoUping;
            }
        }



        if(tempOrderCachePo == canOrderCachePo){
            tempOrderCachePo = null;
        }

        boolean isNotNet = false;
        boolean isHasUpData = false;
        if(canOrderCachePo!=null) {
            isHasUpData = true;
            boolean isSuccess = updata(canOrderCachePo.steelyardInfo,canOrderCachePo.orderEntity);
            System.out.println("====sz 提交订单成功？"+isSuccess);
            isNotNet = !isSuccess;






            synchronized (SZOrderUpTask.this) {
                orderCachePoUping = null;
            }
        }


        long sleepTime = 110;
        if(!isHasUpData){

            sleepTime = 4*1000;
        }else if(isNotNet){
            sleepTime = 5*1000;
        }

        sleepTime = sleepTime - (SystemClock.uptimeMillis() - startTime);

        if(sleepTime >= 100){
            try {
                Thread.sleep(sleepTime);
            }catch (Exception e){}
        }
    }







    private boolean updata(SteelyardInfo steelyardInfo, OrderEntity orderEntity) {
        List<SZWeightInfo> szWeightInfos = NewDataUpParse.parseSZWeightInfo(steelyardInfo, orderEntity);
        String json = null;
        if (!CollectionHelp.isEmpty(szWeightInfos)) {
            json = NewSZApi.submitWeightInfo(steelyardInfo, szWeightInfos.toArray(new SZWeightInfo[szWeightInfos.size()]),  null, true);

//            json = NetworkStateModule.getInstance().getIsNetworkOK()? NewSZApi.submitWeightInfo(steelyardInfo, szWeightInfos.toArray(new SZWeightInfo[szWeightInfos.size()]),  null, true):null;
            try {
                handleSubmitWeightInfo(steelyardInfo, orderEntity, json, szWeightInfos);
            }catch (Exception e){
                e.printStackTrace();;
            }
        } else {
            json = "";
        }
        return json != null;
    }




    private void handleSubmitWeightInfo(SteelyardInfo steelyardInfo, OrderEntity orderEntity, String json, List<SZWeightInfo> szWeightInfos) {
        if (!ExpandConfig.instance.isUI()) {

            return;
        }
        boolean isUpImg = false;


        if (json == null) {

            cacheUpOrder(steelyardInfo, orderEntity);
        } else {
            Set<String> successorderTime = parseSuccessorderTime(json);

            if (successorderTime != null) {
                final List<SZWeightInfo> upszWeightInfos = new ArrayList<>(successorderTime.size());
                for (SZWeightInfo szWeightInfo : szWeightInfos) {
                    if (successorderTime.contains(szWeightInfo.orderTime)) {
                        upszWeightInfos.add(szWeightInfo);
                    }
                }

                if (AppConfig.isOrderImgToSZ)
                if (!CollectionHelp.isEmpty(upszWeightInfos)) {
                    isUpImg = true;



                            submitWeightInfoImg(orderEntity ,szWeightInfos);


                }

            }

        }

        if(!isUpImg){
            holdSizeCacheUpImg(null);
        }
    }



    private Set<String> parseSuccessorderTime(String json) {

        Set<String> successorderTime = null;
        try {
            JsonP1 jsonP = new JsonP1(new JsonParser().parse(json));
            JsonArray jsonElements = jsonP.get("successItems",true).getAsJsonArray();

            int size = jsonElements == null ? 0 : jsonElements.size();
            if (size != 0) {
                successorderTime = new HashSet<>(size);
            }
            for (int i = 0; i < size; i++) {
                successorderTime.add(jsonElements.get(i).getAsJsonObject().get("orderTime").getAsString());
            }
        } catch (Exception e) {
        }

        return successorderTime;
    }








    private String getCacheUpOrder() {

        try {
            File[] files = new File(AppConfig.DataFile.orderCacheUpSZFileDir).listFiles();
            File file = files[0];
            String json = IOHelp.parserInputStreamToString(new FileInputStream(file), "utf-8").toString();
            file.delete();
            return json;

        } catch (Exception e) {
        }
        return null;
    }



    private int cacheUpOrderSize() {
        try {
            return new File(AppConfig.DataFile.orderCacheUpSZFileDir).list().length;
        } catch (Exception e) {
        }

        return 0;
    }




    private void holdSizeCacheUpOrder(){
        try {
            int cacheUpFailOrderSize = cacheUpOrderSize();
            if (cacheUpFailOrderSize > 1500) {
                deleteFile(AppConfig.DataFile.orderCacheUpSZFileDir, 500);
            }
        } catch (Exception e) {
        }
    }


    private void cacheUpOrder(SteelyardInfo steelyardInfo, OrderEntity orderEntity) {
        if (StringHelp.isEmpty(orderEntity.orderNum)) return;

        holdSizeCacheUpOrder();
        try {
            File file = new File(AppConfig.DataFile.orderCacheUpSZFileDir + orderEntity.orderNum);
            File parentFile = file.getParentFile();
            if (!parentFile.exists())
                parentFile.mkdirs();

            if (file.exists()) return;
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            file.createNewFile();

            fileOutputStream.write(GsonHelp.toJson(new OrderCachePo(steelyardInfo, orderEntity)).getBytes("utf-8"));
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
        }
    }


    private static class OrderCachePo {
        public OrderCachePo() {
        }

        public OrderCachePo(SteelyardInfo steelyardInfo, OrderEntity orderEntity) {
            this.steelyardInfo = steelyardInfo;
            this.orderEntity = orderEntity;
        }

        @SerializedName("st")
        public SteelyardInfo steelyardInfo;
        @SerializedName("o")
        public OrderEntity orderEntity;
    }







    private final ReentrantLock imageFileLock = new ReentrantLock();



    private void submitWeightInfoImg(OrderEntity orderEntity, List<SZWeightInfo> szWeightInfos) {

        List<SZWeightImg> szWeightImgs = new ArrayList<>(szWeightInfos.size());

        File[] files = new File[szWeightInfos.size()];


        try {
            imageFileLock.lock();

            int i = 0;
            for (SZWeightInfo szWeightInfo : szWeightInfos) {
                if (szWeightInfo == null) continue;
                SZWeightImg szWeightImg = new SZWeightImg();
//                szWeightImg.deviceID = szWeightInfo.deviceNo;
                szWeightImg.deviceNo = szWeightInfo.deviceNo;
                szWeightImg.orderNo = szWeightInfo.orderNo;
                szWeightImg.orderTime = szWeightInfo.orderTime;
                File file = new File(AppConfig.DataFile.getOrderImgUpSZFilePath(orderEntity.createTime, szWeightInfo.goodimg_on));
                try {
                    szWeightImg.image = Base64Common.encode(IOHelp.readFull(new FileInputStream(file), (int) file.length()));
                    System.out.println("====sz 找到要提交的图片"+file.getAbsolutePath());
                } catch (Exception e) {
                    System.out.println("====sz 找不到要提交的图片"+file.getAbsolutePath());
                    continue;
                }
                szWeightImgs.add(szWeightImg);
                files[i] = file;
                i++;

            }
        } finally {
            imageFileLock.unlock();

        }

        if (CollectionHelp.isEmpty(szWeightImgs)) return;

        String json = NewSZApi.submitWeightImg(szWeightImgs.toArray(new SZWeightImg[szWeightImgs.size()]), null, true);


        boolean isSuccess = json != null;



        holdSizeCacheUpImg(files);

    }



    private void holdSizeCacheUpImg(File[] deleteFiles){

        System.out.println("=====sz 删除图片"+CollectionHelp.getSize(deleteFiles));

        try {
            imageFileLock.lock();
            File orderImgUpSZFileDirFile = new File(AppConfig.DataFile.orderImgUpSZFileDir);

            if (deleteFiles != null) {

                for (File f : deleteFiles) {
                    if (f != null) {
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }



            if(orderImgUpSZFileDirFile.list().length > 1500){
                System.out.println("=====sz 删除1500图片");


                if (!isSubmitWeightInfoing() && tempOrderCachePo == null && cacheUpOrderSize() == 0) {

                    FileHelper.deleteFileOrFolder(new File(AppConfig.DataFile.orderImgUpSZFileDir));
                }else {
                    deleteFile(AppConfig.DataFile.orderImgUpSZFileDir, 500);
                }
            }
        } catch (Exception e) {
        } finally {
            imageFileLock.unlock();
        }
    }






    public static File[] orderByDate(String filePath) {
        File file = new File(filePath);
        File[] files = file.listFiles();
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File f1, File f2) {
                long diff = f1.lastModified() - f2.lastModified();
                if (diff > 0)
                    return 1;
                else if (diff == 0)
                    return 0;
                else
                    return -1;
            }

            public boolean equals(Object obj) {
                return true;
            }

        });
        return files;

//            System.out.println(files[i].getName());
//            System.out.println(new Date(files[i].lastModified()));


    }

    private void deleteFile(String dir,int size) {

        try {
            File[] files = orderByDate(dir);
            int start = files.length - size;
            if (start >= 0)
                for (int i = start; i < files.length; i++) {
                    files[i].delete();
                }
        } catch (Exception e) {
        }
    }

}
